package io.github.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import io.github.dao.SysBookDao;
import io.github.entity.SysBookEntity;
import io.github.service.SysBookService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @Author: Max
 * @Date: 2019/10/9 11:07
 */

@Service
public class SysBookServiceImpl extends ServiceImpl<SysBookDao, SysBookEntity> implements SysBookService {

    @Resource
    SysBookDao dao;


    @Override
    public Page<SysBookEntity> selectByPage(Integer offset, Integer limit, String name,String orgId,String depId,String number,Boolean root) {
        Wrapper wrapper = new EntityWrapper();
        if(StringUtils.isNotBlank(name)){
            wrapper.like("name",name);
        }


        if(!root){
            if(StringUtils.isNotBlank(depId)){
//            orgids = dao.findChildList(orgId);
                wrapper.eq("dep_id",depId);
            }else if(StringUtils.isNotBlank(orgId)){
                wrapper.eq("org_id",orgId);
            }
        }


//       *****************************
        if(StringUtils.isNotBlank(number)){
            if(number.startsWith("_")){
                //表示用户采用的正则匹配，那么查询就是简单的模糊查询
                wrapper.like("number_section",number);
                wrapper.orderBy("id",false);
                Page<SysBookEntity> page = new Page<>(offset,limit);
                return this.selectPage(page,wrapper);

            }else{
                //表示用户输入的是具体的号码，那么用户希望 通过 number 来找到匹配的规则
                //1.首先需要获取数据库所有的字段
                wrapper.addFilter("(select "+number+" REGEXP REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(number_section,'_','^'),'!','$'),'.','X'),'X','[0-9]'),'Z','[1-9]'),'N','[2-9]')) =1");
                wrapper.orderBy("id",false);
                Page<SysBookEntity> page = new Page<>(offset,limit);
                return this.selectPage(page,wrapper);
            }

        }else{
            wrapper.orderBy("id",false);
            Page<SysBookEntity> page = new Page<>(offset,limit);
            return this.selectPage(page,wrapper);
        }

    }

    @Override
    public void save(SysBookEntity entity) {
        baseMapper.insert(entity);
    }


}
